package com.zyh.stu.system.dao.impl;

import com.zyh.stu.system.dao.StudentDao;
import com.zyh.stu.system.domain.Student;

import java.util.ArrayList;

public class StudentDaoImpl implements StudentDao {
    public static final ArrayList<Student> STU_LIST = new ArrayList<Student>();

    static {
        STU_LIST.add(new Student("001", "zyh", 20, "2004-10-21"));
        STU_LIST.add(new Student("002", "abc", 21, "2003-10-21"));
        STU_LIST.add(new Student("003", "def", 22, "2002-10-21"));
    }

    //添加学生
    @Override
    public boolean add(Student student) {
        boolean add = STU_LIST.add(student);
        return add;
    }

    //删除学生
    @Override
    public boolean delete(String id) {
        // 找到指定id的学生在集合中的位置
        int stuIndex = findById(id);
        if (stuIndex == -1) {
            return false;
        }
        //走到此处说明id存在
        STU_LIST.remove(stuIndex);
        return true;
    }

    //修改学生
    @Override
    public boolean update(Student student) {
        int stuIndex = findById(student.getSid());
        STU_LIST.set(stuIndex, student);
        return true;
    }

    //查询学生
    @Override
    public void findAll() {
        if (STU_LIST.size() == 0) {
            System.out.println("请先添加学生在进行查询");
            return;
        }
        //打印表头
        System.out.println("编号\t姓名\t年龄\t生日");
        for (Student student : STU_LIST) {
            System.out.println(student.getSid() + "\t" + student.getName() + "\t" + student.getAge() + "\t" + student.getBirthday());
        }
    }

    //根据id获取学生索引
    @Override
    public int findById(String id) {
        //假设指定id的学生在集合中不存在
        int index = -1;
        for (int i = 0; i < STU_LIST.size(); i++) {
            //获取集合中每一个学生对象
            Student student = STU_LIST.get(i);
            //判断student的id是否和传过来的id相同
            if (student.getSid().equals(id)) {
                index = i;
                break;
            }
        }
        return index;
    }
}
